<template>
	<view class="container">
		<view class="formsty">
			<view style="margin-bottom: 30px; margin-left: 80px;">
				<text>欢迎回来</text>
			</view>
			<view>
				<uni-forms-item label="账号">
					<uni-easyinput class="btnsty" v-model="formState.username" prefixIcon="person"
						placeholder="请输入用户名"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item label="密码">
					<uni-easyinput class="btnsty" type="password" v-model="formState.password" prefix-icon="locked"
						placeholder="请输入密码"></uni-easyinput>
				</uni-forms-item>
				<button class="button" @click="submitForm">登 录</button>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { defineComponent, reactive, ref, UnwrapRef } from 'vue';

import { useUserStore } from "@/store/user";

// 用户状态(缓存)
const uStore = useUserStore();

interface iUserLogin {
	username: string;
	password: string;
	remember: boolean;
	errMsgFlag: boolean;
	errMsg: string;
}

const formState: UnwrapRef<iUserLogin> = reactive({
	username: '',
	password: '',
	remember: true,
	errMsgFlag: false,
	errMsg: '',
});


function submitForm() {
	uni.request({
		url: "/api/login?username=" + formState.username + "&password=" + formState.password,
		method: 'GET',
	})
		.then((res: any) => {
			if (res.statusCode == 200) {

				// 如果登录勾选了“记住密码”则在回到登录页面时，要将用户名和密码回显到对应的文本框中
				localStorage.setItem('username', formState.username)
				localStorage.setItem('password', formState.password)
				localStorage.setItem('remember', formState.remember + '')

				let code = res.data.code // 响应的状态码（0：正常；其他为异常）
				let body = res.data // 数据结构（Json格式）
				if (0 == code) { // 成功

					uStore.clearUserState();

					formState.errMsg = '';
					formState.errMsgFlag = false;
					const data = body.data;
					localStorage.setItem('nickName', data.nickName)
					localStorage.setItem('userName', data.userName)
					localStorage.setItem('avatar', data.avatar)
					// 登录成功后记录token和refreshToken
					const userData: any = { token: data.token, refreshToken: data.refreshToken }

					// 存储登录信息到storage
					uStore.setUserInfo(userData)

					// 登录成功-跳转页面
					uni.switchTab({
						url: '/pages/index/index',
					})
					// uni.navigateTo({
					// 	url:'/pages/index/index',
					// })
					// 提示登录成功
					uni.showToast({
						title: '登录成功',
						// icon: 'success',
						// mask: true
					})
				} else {
					formState.errMsg = body.msg;
					formState.errMsgFlag = true;
					// 显示错误提示
					uni.showToast({
						title: body.msg,
						icon: 'none',
						duration: 2000
					});
				}
			}
		})
}
</script>

<style>
.formsty {
	width: 70%;
	margin-top: 180px;
	margin-left: 60px;
}

.btnsty {
	margin-left: -28px;
}
</style>